import paho.mqtt.client as mqtt
from application import settings
import json
import time
import uuid
import threading

def on_connect(mqtt_client, userdata, flags, rc):
    if rc == 0:
        print('Connected successfully',mqtt_client,time.localtime(time.time()))
        # mqtt_client.subscribe('django/mqtt')
    else:
        print('Bad connection. Code:', rc)


def on_message(mqtt_client, userdata, msg):
    print(f'Received message on topic: {msg.topic} with payload: {msg.payload}')

# 开锁
def unlock(device):
    timestamp = int(time.time()*1000)
    uuid_str = str(uuid.uuid4()).replace('-','')
    data = {
        "device_id":device
    }
    json_obj = {
        "timestamp":timestamp,
        "messageId":uuid_str,
        "data": data
    }
    json_str = json.dumps(json_obj)
    print("send json",json_str)
    client.publish(settings.MQTT_UNLOCK_TOPIC,payload=json_str,qos=0)


# 微信用户开箱
def openbox(device):
    timestamp = int(time.time()*1000)
    uuid_str = str(uuid.uuid4()).replace('-','')
    data = {
        "device_id":device
    }
    json_obj = {
        "timestamp":timestamp,
        "messageId":uuid_str,
        "data": data
    }
    json_str = json.dumps(json_obj)
    print("send json",json_str)
    print("client",client)
    client.publish(settings.MQTT_OPENBOX_TOPIC,payload=json_str,qos=0)


client = mqtt.Client(client_id=settings.CLIENT_ID)
def start_mqtt_client():
    print("创建的client",client)
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD)
    client.connect(
        host=settings.MQTT_SERVER,
        port=settings.MQTT_PORT,
        keepalive=settings.MQTT_KEEPALIVE
    )
    client.loop_start()
    # client.loop_forever()

# client_thread = threading.Thread(target=start_mqtt_client)
# client_thread.daemon = True
# client_thread.start()
# start_mqtt_client()